//
//  RFRadioView.m
//  RadioFree
//
//  Created by zhaojianguo-PC on 14-5-23.
//  Copyright (c) 2014年 xiaozi. All rights reserved.
//

#import "RFRadioView.h"
#import "FSAudioStream.h"
#import "FSAudioController.h"
#import "FSPlaylistItem.h"
#import "UIView+Additions.h"


@implementation RFRadioView
@synthesize selectedPlaylistItem = _selectedPlaylistItem;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor colorWithRed:232.f/255.f green:184.f/255.f blue:10.f/255.f alpha:1.f];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(audioStreamStateDidChange:)
                                                     name:FSAudioStreamStateChangeNotification
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(audioStreamErrorOccurred:)
                                                     name:FSAudioStreamErrorNotification
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(audioStreamMetaDataAvailable:)
                                                     name:FSAudioStreamMetaDataNotification
                                                   object:nil];
        
        audioController = [[FSAudioController alloc] init];
        
        progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(10, 20, frame.size.width-15-100, progressSlider.size.height)];
        progressSlider.minimumTrackTintColor = [UIColor blueColor];
        progressSlider.maximumTrackTintColor = [UIColor whiteColor];
        [progressSlider addTarget:self action:@selector(seek) forControlEvents:UIControlEventValueChanged];
        [self addSubview:progressSlider];
        
        _currentPlaybackTime = [[UILabel alloc] initWithFrame:CGRectMake(progressSlider.origin.x+progressSlider.size.width, 5, 100, 25)];
        _currentPlaybackTime.font =[UIFont boldSystemFontOfSize:14.0f];
        _currentPlaybackTime.textAlignment = NSTextAlignmentCenter;
        _currentPlaybackTime.backgroundColor = [UIColor clearColor];
        _currentPlaybackTime.textColor = [UIColor whiteColor];
        _currentPlaybackTime.text = @"--:--/--:--";
        [self addSubview:_currentPlaybackTime];
        
        pauseButton = [UIButton buttonWithType:UIButtonTypeCustom];
        pauseButton.frame = CGRectMake(frame.size.width-60, progressSlider.origin.y+progressSlider.size.height+20, 50, 50);
        [pauseButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        [pauseButton addTarget:self action:@selector(pause) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:pauseButton];

        
        playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        playButton.frame = CGRectMake(frame.size.width-60, progressSlider.origin.y+progressSlider.size.height+20, 50, 50);
        [playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
        [playButton addTarget:self action:@selector(play) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:playButton];
        
        
        _statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(progressSlider.origin.x, progressSlider.size.height+progressSlider.origin.y+20, frame.size.width-playButton.size.width-25, 50)];
        _statusLabel.backgroundColor = [UIColor colorWithWhite:255.0f alpha:0.4];
        _statusLabel.textAlignment = NSTextAlignmentCenter;
        _statusLabel.font = [UIFont boldSystemFontOfSize:12.0f];
        _statusLabel.textColor = [UIColor blackColor];
        _statusLabel.numberOfLines = 3;
        [self addSubview:_statusLabel];
    }
    return self;
}
- (void)play{
    if ([audioController.url length]!=0) {
        if (_paused) {
            [audioController pause];
            _paused = NO;
        } else {
            [audioController play];
            _paused = YES;
        }
        playButton.hidden = YES;
        pauseButton.hidden = NO;
    }
}

- (void)pause{
    [audioController pause];
    _paused = YES;
    
    playButton.hidden = NO;
    pauseButton.hidden = YES;
}

- (void)seek {
    _seekToPoint = progressSlider.value;
    [_progressUpdateTimer invalidate],
    _progressUpdateTimer = nil;
    [_playbackSeekTimer invalidate],
    _playbackSeekTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                                                           target:self
                                                                                         selector:@selector(seekToNewTime)
                                                                                         userInfo:nil
                                                                                          repeats:NO];
}


- (void)setSelectedPlaylistItem:(FSPlaylistItem *)selectedPlaylistItem {
    if (_selectedPlaylistItem != selectedPlaylistItem) {
        _selectedPlaylistItem = selectedPlaylistItem;
        [audioController stop];
        audioController.url = self.selectedPlaylistItem.url;//@"http://www.hnystf.com/music/3.mp3";//
        NSLog(@"%@",audioController.url);
        [audioController play];
        _progressUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                                target:self
                                                              selector:@selector(updatePlaybackProgress)
                                                              userInfo:nil
                                                               repeats:YES];
    }
}

- (FSPlaylistItem *)selectedPlaylistItem {
    return _selectedPlaylistItem;
}
- (void)audioStreamMetaDataAvailable:(NSNotification *)notification
{
    NSDictionary *dict = [notification userInfo];
    NSDictionary *metaData = [dict valueForKey:FSAudioStreamNotificationKey_MetaData];
    NSString *streamTitle = [metaData objectForKey:@"StreamTitle"];
    
done:;
    _statusLabel.text = streamTitle;
}
- (void)audioStreamErrorOccurred:(NSNotification *)notification
{
    NSDictionary *dict = [notification userInfo];
    int errorCode = [[dict valueForKey:FSAudioStreamNotificationKey_Error] intValue];
    
    switch (errorCode) {
        case kFsAudioStreamErrorOpen:
            _statusLabel.text = @"Cannot open the audio stream";
            break;
        case kFsAudioStreamErrorStreamParse:
            _statusLabel.text = @"Cannot read the audio stream";
            break;
        case kFsAudioStreamErrorNetwork:
            _statusLabel.text = @"Network failed: cannot play the audio stream";
            break;
        default:
            _statusLabel.text = @"Unknown error occurred";
            break;
    }
}
- (void)audioStreamStateDidChange:(NSNotification *)notification {
    NSString *statusRetrievingURL = @"Retrieving stream URL";
    NSString *statusBuffering = @"Buffering...";
    NSString *statusSeeking = @"Seeking...";
    NSString *statusEmpty = @"";
    
    NSDictionary *dict = [notification userInfo];
    int state = [[dict valueForKey:FSAudioStreamNotificationKey_State] intValue];
    
    switch (state) {
        case kFsAudioStreamRetrievingURL:
//            [_activityIndicator startAnimating];
            _statusLabel.text = statusRetrievingURL;
//            [_statusLabel setHidden:NO];
            progressSlider.enabled = NO;
            playButton.hidden = YES;
            pauseButton.hidden = NO;
            _paused = NO;
            break;
            
        case kFsAudioStreamStopped:
//            [_activityIndicator stopAnimating];
            _statusLabel.text = statusEmpty;
            progressSlider.enabled = NO;
            playButton.hidden = NO;
            pauseButton.hidden = YES;
            _paused = NO;
            break;
            
        case kFsAudioStreamBuffering:
            _statusLabel.text = statusBuffering;
//            [_activityIndicator startAnimating];
//            [_statusLabel setHidden:NO];
            progressSlider.enabled = NO;
            playButton.hidden = YES;
            pauseButton.hidden = NO;
            _paused = NO;
            break;
            
        case kFsAudioStreamSeeking:
            _statusLabel.text = statusSeeking;
//            [_activityIndicator startAnimating];
//            [_statusLabel setHidden:NO];
            progressSlider.enabled = NO;
            playButton.hidden = YES;
            pauseButton.hidden = NO;
            _paused = NO;
            break;
            
        case kFsAudioStreamPlaying:
//            [_activityIndicator stopAnimating];
            if ([_statusLabel.text isEqualToString:statusBuffering] ||
                [_statusLabel.text isEqualToString:statusRetrievingURL] ||
                [_statusLabel.text isEqualToString:statusSeeking]) {
                _statusLabel.text = statusEmpty;
            }
            progressSlider.enabled = YES;
//
            if (!_progressUpdateTimer) {
                _progressUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                                        target:self
                                                                      selector:@selector(updatePlaybackProgress)
                                                                      userInfo:nil
                                                                       repeats:YES];
            }
//
            playButton.hidden = YES;
            pauseButton.hidden = NO;
            _paused = NO;
            
            break;
            
        case kFsAudioStreamFailed:
//            [_activityIndicator stopAnimating];
            progressSlider.enabled = NO;
            playButton.hidden = NO;
            pauseButton.hidden = YES;
            _paused = NO;
            break;
    }
}

- (void)updatePlaybackProgress
{
    if (audioController.stream.continuous) {
        progressSlider.enabled = NO;
        progressSlider.value = 0;
    } else {
        double s = audioController.stream.currentTimePlayed.minute * 60 + audioController.stream.currentTimePlayed.second;
        double e = audioController.stream.duration.minute * 60 + audioController.stream.duration.second;
        progressSlider.enabled = YES;
        progressSlider.value = s / e;
        FSStreamPosition cur = audioController.stream.currentTimePlayed;
        FSStreamPosition end = audioController.stream.duration;
        _currentPlaybackTime.text = [NSString stringWithFormat:@"%i:%02i / %i:%02i",
                                         cur.minute, cur.second,
                                         end.minute, end.second];
    }
}

- (void)seekToNewTime
{
    progressSlider.enabled = NO;
    unsigned u = (audioController.stream.duration.minute * 60 + audioController.stream.duration.second) * _seekToPoint;
    unsigned s,m;
    s = u % 60, u /= 60;
    m = u;
    FSStreamPosition pos;
    pos.minute = m;
    pos.second = s;
    [audioController.stream seekToPosition:pos];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
